const CategoryModel = require('../models/categoryModel');
const appError = require('../utils/appError');
const { listToTree } = require('../utils/utils');

class CategoryService {
  // 检查分类名是否已存在
  async isNameExist (name) {
    const category = await CategoryModel.findOne({ name });
    return !!category;
  }

  // 创建分类
  async create(data, created_by) {
    // 验证必填字段
    if (!data.name || !data.code) {
      appError(400, '分类名和分类码都是必填项', {
        name: !data.name ? '分类名是必填项' : null,
        code: !data.code ? '分类码是必填项' : null
      });
    }

    // 检查分类名是否存在
    const exists = await this.isNameExist(data.name);
    if (exists) {
      appError(409, '分类名已存在');
    }

    // 创建新分类
    const newCategory = new CategoryModel({ ...data, created_by });
    await newCategory.save();
    return newCategory;
  }

  // 更新分类
  async update(data, updated_by) {
    const category_id = data.id
    const category = await CategoryModel.findOne({ category_id });
    if (!category) {
      appError(400, '分类不存在');
    }
    await CategoryModel.updateOne({ category_id }, { $set: { ...data, updated_by } });
    return await CategoryModel.findOne({ category_id });
  }

  // 删除分类
  async delete(category_id) {
    const category = await CategoryModel.findOne({ category_id });
    if (!category) {
      appError(400, '分类不存在');
    }
    await CategoryModel.deleteOne({ category_id });
  }

  // 获取单个分类
  async findOne(category_id) {
    return await CategoryModel.findOne({ category_id });
  }

  // 获取所有分类
  async findAll(type) {
    const categories = await CategoryModel.find();
    const data = categories.map(category => {
      return {
        name: category.name,
        code: category.code,
        parent_id: category.parent_id,
        level: category.level,
        sort_order: category.sort_order,
        status: category.status,
        is_visible: category.is_visible,
        created_at: category.created_at,
        updated_at: category.updated_at,
        created_by: category.created_by,
        updated_by: category.updated_by,
        category_id: category.category_id
      }
    })

    if (type !== 'tree') {
      return data;
    }

    return listToTree(data, 'parent_id', 'category_id')
  }
}

module.exports = new CategoryService();